package com.yugao.fintech.antelope.pay.payment.factory;

import com.yugao.fintech.antelope.base.config.GlobalProperties;
import com.yugao.fintech.antelope.pay.constant.IfCodeEnum;
import com.yugao.fintech.antelope.pay.payment.model.bo.IClientWrapper;
import com.yugao.fintech.antelope.pay.payment.model.params.IsvParams;
import com.yugao.fintech.antelope.pay.payment.model.params.IsvsubMchParams;
import com.yugao.fintech.antelope.pay.payment.model.params.NormalMchParams;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.assistant.crypto.AesCrypto;
import com.yugao.fintech.framework.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public abstract class AbstractPayFactory {

    @Autowired
    private GlobalProperties globalProperties;

    protected AesCrypto aesCrypto;

    @PostConstruct
    public void abstractPayFactoryInit() {
        aesCrypto = new AesCrypto(globalProperties.getSecretKey());
    }


    private static final Map<IfCodeEnum, AbstractPayFactory> payFactoryMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        log.info("init payFactoryMap");
        payFactoryMap.clear();
        ApplicationContext applicationContext = SpringUtils.getApplicationContext();
        applicationContext.getBeansOfType(AbstractPayFactory.class)
                .values().forEach(e -> payFactoryMap.put(e.getIfCode(), e));
    }

    public static AbstractPayFactory getInstance(IfCodeEnum ifCodeEnum) {
        if (Objects.isNull(ifCodeEnum)) {
            throw new BizException("ifCodeEnum is null");
        }
        if (!payFactoryMap.containsKey(ifCodeEnum)) {
            throw new BizException("未实现 {} 对应的工厂", ifCodeEnum.name());
        }
        return payFactoryMap.get(ifCodeEnum);
    }

    public abstract IfCodeEnum getIfCode();

    public abstract IClientWrapper buildClientWrapper(IsvParams isvParams);

    public abstract IClientWrapper buildClientWrapper(NormalMchParams normalMchParams);

    public abstract IsvParams buildIsvParams(String paramsStr);

    public abstract NormalMchParams buildNormalMchParams(String paramsStr);

    /**
     * 特约商户参数定义
     */
    public abstract IsvsubMchParams buildIsvsubMchParams(String paramsStr);

}
